// pay-popup.js
Component({
    properties: {
        show: {
            type: Boolean,
            value: false
        },
        item: {
            type: Object,
            value: {
                id: null,
                image: '',
                title: '',
                price: '0.00',
                count: 1,
            }
        }
    },

    data: {
        total: '0.00',
        internalItem: {} // 用于控制内部 item 数据（避免 props 修改）
    },

    observers: {
        'item': function (item) {
            if (item && item.price) {
                const parsedItem = {
                    ...item,
                    count: item.count || 1
                };
                this.setData({ internalItem: parsedItem }, this.updateTotal);
            }
        }
    },

    methods: {
        closePopup() {
            this.triggerEvent('close');
        },

        increaseCount() {
            const newCount = this.data.internalItem.count + 1;
            const newItem = { ...this.data.internalItem, count: newCount };
            this.setData({ internalItem: newItem }, this.updateTotal);
        },

        decreaseCount() {
            const newCount = Math.max(1, this.data.internalItem.count - 1);
            const newItem = { ...this.data.internalItem, count: newCount };
            this.setData({ internalItem: newItem }, this.updateTotal);
        },

        updateTotal() {
            const item = this.data.internalItem || {};
            const price = parseFloat(item.price) || 0;
            const count = parseInt(item.count) || 1;
            const total = (price * count).toFixed(2);
            this.setData({ total });
        },

        onPay() {
            wx.showToast({
                title: '模拟支付中...',
                icon: 'none'
            });
            this.triggerEvent('pay', {
                item: this.data.internalItem,
                total: this.data.total
            });
        }
    }
});
